<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否上架" prop="shelfStatus">
        <el-select v-model="queryParams.shelfStatus" placeholder="是否上架" clearable>
          <el-option v-for="dict in dict.type.is_or_not" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:product:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:product:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:product:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:product:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" width="50" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="封面" align="center" prop="cover" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="细节图" align="center" prop="detailDrawing" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.detailDrawing" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="产品颜色" align="center" prop="color" width="100">
        <template slot-scope="scope">
          <div
            :style="{ backgroundColor: scope.row.color, width: '20px', height: '20px', margin: '0 auto', borderRadius: '4px' }">
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="产品颜色" align="center" prop="color" width="100">
        <template slot-scope="scope">
          <el-color-picker v-model="scope.row.color" show-alpha></el-color-picker>
        </template>
      </el-table-column> -->
      <el-table-column label="保修期(天)" align="center" prop="baoxiu" width="100" />

      <el-table-column label="上/下架" align="center" prop="shelfStatus" width="100">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.shelfStatus" placement="top">
            <el-switch @change="toggleShelfStatus(scope.row, scope.row.id, scope.row.shelfStatus)"
              v-model="scope.row.shelfStatus" active-color="#13ce66" inactive-color="#ff4949" active-value="是"
              inactive-value="否">
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="销量" align="center" prop="saleNum" width="100" />
      <!-- <el-table-column label="描述" align="center" prop="info" /> -->
      <el-table-column label="返利积分" align="center" prop="pointRebate" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="skuUpdate(scope.row)"
            v-hasPermi="['product:product:edit']">SKU</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:product:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['product:product:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <image-upload v-model="form.cover" :limit="1" />
        </el-form-item>
        <el-form-item label="细节图" prop="detailDrawing">
          <image-upload v-model="form.detailDrawing" />
        </el-form-item>
        <el-form-item label="属性模板" prop="attrId">
          <template>
            <el-select v-model="form.attrId" filterable remote reserve-keyword placeholder="选择属性模板"
              :remote-method="attrQuery" :loading="loading">
              <el-option v-for="item in attrOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="销量" prop="saleNum">
          <!-- <el-input v-model="form.saleNum" placeholder="请输入销量" /> -->
          <el-input-number v-model="form.saleNum" :min="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="返利积分" prop="pointRebate">
          <el-input-number v-model="form.pointRebate" :min="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="保修期(天)" prop="baoxiu">
          <el-input-number v-model="form.baoxiu" :min="1" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="产品颜色" prop="color">
          <el-color-picker v-model="form.color" show-alpha :predefine="predefineColors">
          </el-color-picker>
        </el-form-item>
        <el-form-item label="描述">
          <editor v-model="form.info" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改SKU -->
    <el-dialog :title="skuTitle" :visible.sync="skuOpen" append-to-body :fullscreen="true" style="min-width: 90%;"
      v-loading="loading">
      <el-form ref="skuForm" :model="skuForm" :rules="skuRules">
        <!-- 表格 -->
        <el-table ref="mytable" border resizable :data="dataList" height="750">
          <!-- <el-table-column :label="'序号'" :key="'index'" align="center">
            <template v-slot="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column> -->
          <el-table-column :label="item.label" :prop="item.prop" :key="index" v-for="(item, index) in headArray"
            :align="'center'" :width="item.label === '图片' ? '200px' : ''"
            v-if="item.label !== 'id' && item.label !== '产品id'">
            <template v-slot="{ row }">
              <template v-if="item.label === 'id'">
                {{ row[item.prop] }}
              </template>
              <template v-else-if="item.label === '产品id'">
                {{ row[item.prop] }}
              </template>
              <template v-else-if="item.label === 'skuCode'">
                <el-input v-model="row[item.prop]" placeholder="SKU" @input="refreshTableData()"></el-input>
              </template>
              <template v-else-if="item.label === '图片'">
                <image-upload v-model="row[item.prop]" @input="refreshTableData()" :limit="1" />
              </template>
              <template v-else-if="item.label === '成本价'">
                <el-input type="number" v-model="row[item.prop]" @input="refreshTableData()"
                  placeholder="0.00"></el-input>
              </template>
              <template v-else-if="item.label === '价格'">
                <el-input type="number" v-model="row[item.prop]" @input="refreshTableData()"
                  placeholder="0.00"></el-input>
              </template>
              <template v-else-if="item.label === '原价'">
                <el-input type="number" v-model="row[item.prop]" @input="refreshTableData()"
                  placeholder="0.00"></el-input>
              </template>
              <template v-else-if="item.label === '折扣'">
                <el-input type="number" v-model="row[item.prop]" @input="refreshTableData()"
                  placeholder="0.00"></el-input>
              </template>
              <template v-else-if="item.label === '库存'">
                <el-input type="number" v-model="row[item.prop]" @input="refreshTableData()"
                  placeholder="0.00"></el-input>
              </template>
              <template v-else-if="item.label === '重量(KG)'">
                <el-input type="number" v-model="row[item.prop]" @input="refreshTableData()"
                  placeholder="0.00"></el-input>
              </template>
              <template v-else-if="item.label === '体积(m²)'">
                <el-input type="number" v-model="row[item.prop]" @input="refreshTableData()"
                  placeholder="0.00"></el-input>
              </template>
              <template v-else-if="item.label === '是否显示'">
                <el-tooltip :content="row[item.prop]" placement="top">
                  <el-switch v-model="row[item.prop]" active-color="#13ce66" inactive-color="#ff4949" active-value="是"
                    active-text="是" inactive-value="否" inactive-text="否" @input="refreshTableData()">
                  </el-switch>
                </el-tooltip>
              </template>
              <template v-else>
                {{ row[item.prop] }}
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSkuForm">确 定</el-button>
        <el-button @click="cancelSku">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/product/product";
import { listAttr, getAttr, delAttr, addAttr, updateAttr } from "@/api/product/attr";
import { listSku, addProductSkuList } from "@/api/product/sku";


export default {
  name: "Product",
  dicts: ['is_or_not'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 描述时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        shelfStatus: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "change" }
        ],
        attrId: [
          { required: true, message: "请选择属性模板", trigger: "change" }
        ],
      },
      // SKU
      skuTitle: "",
      skuOpen: false,
      skuRules: {
      },
      skuForm: {},
      headArray: [],
      skuList: [],
      originalArray: [],
      skuAttr: [
        { label: 'id', prop: 'id' },
        { label: '产品id', prop: 'productId' },
        { label: 'skuCode', prop: 'skuCode' },
        { label: '图片', prop: 'icon' },
        { label: '成本价', prop: 'costPrice' },
        { label: '价格', prop: 'price' },
        { label: '原价', prop: 'originalPrice' },
        { label: '折扣', prop: 'discount' },
        { label: '库存', prop: 'stockQuantity' },
        { label: '重量(KG)', prop: 'weight' },
        { label: '体积(m²)', prop: 'volume' },
        { label: '是否显示', prop: 'isReveal' },
      ],
      inputSku: '',
      dataList: [],
      //属性模板
      attrOptions: [],
      color: 'rgba(255, 69, 0, 0.68)',
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    //分类初始化
    listAttr({
      pageNum:1,
      pageSize:9999
    }).then(response => {
      this.attrOptions = response.rows.map(item => {
        return { value: `${item.name}`, label: `${item.id}：${item.name}` };
      })
    });
  },
  methods: {
    //上下架
    toggleShelfStatus(row, id, status) {
      this.form = { id: id, shelfStatus: (status === '是') ? '是' : '否' };
      updateProduct(this.form).then(response => {
        if (status === '是') {
          this.$modal.msgSuccess("已上架");
        } else {
          this.$modal.msgError("已下架");
        }
        this.getList();
      }).catch(err => {
        // 如果更新出错，将状态设置为相反的值（即关闭状态）
        status = (status === '是') ? '否' : '是';
        row.shelfStatus = status;
        // this.$modal.msgError(err);
      });

    },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        cover: null,
        detailDrawing: null,
        shelfStatus: null,
        saleNum: null,
        info: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？').then(function () {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    //属性模板查询
    attrQuery(query) {
      if (query !== '') {
        this.attrLoading = true;
        setTimeout(() => {
          this.attrLoading = false;
          listAttr({
            pageNum: 1,
            pageSize: 99999,
            name: query
          }).then(response => {
            this.attrOptions = response.rows.map(item => {
              return { value: `${item.name}`, label: `${item.id}：${item.name}` };
            });
          });
        }, 200);
      } else {
        this.attrOptions = [];
      }
    },
    /** sku操作 */
    cancelSku() {
      this.skuOpen = false;
      this.resetSku();
    },

    async skuUpdate(row) {
      this.skuList = [];
      this.dataList = [];
      this.skuOpen = true;
      this.skuTitle = "配置SKU";
      this.loading = true;

      // 获取产品信息
      const response = await getProduct(row.id);
      // 获取属性关键字
      const response2 = await listAttr({
        pageNum: 1,
        pageSize: 1,
        name: response.data.attrId
      });
      const rid = response2.rows[0].id;
      // 获取产品属性
      const res = await getAttr(rid);
      console.log("res", res)

      // 商品属性列表
      this.originalArray = res.data.productAttrValueList;
      this.generateSKU({}, 0);

      // 生成表头
      this.headArray = [
        ...Object.keys(this.skuList[0]).map(key => ({ label: key, prop: key })),
        ...this.skuAttr
      ];

      // 更新SKU列表
      for (const item of this.skuList) {
        const res3 = await listSku({
          pageNum: 1,
          pageSize: 1,
          productId: row.id,
          skuAttribute: JSON.stringify(item)
        });
        item.productId = row.id;
        if (res3.rows && res3.rows.length > 0) {
          var dres = res3.rows[0];
          item.id = dres.id;
          item.skuCode = dres.skuCode;
          item.icon = dres.icon;
          item.costPrice = dres.costPrice;
          item.price = dres.price;
          item.originalPrice = dres.originalPrice;
          item.discount = dres.discount;
          item.stockQuantity = dres.stockQuantity;
          item.weight = dres.weight;
          item.volume = dres.volume;
          item.isReveal = dres.isReveal;
        }
      }
      // 强制更新组件
      this.dataList = this.skuList
      this.loading = false;
    },
    /** 提交按钮 */
    submitSkuForm() {
      this.$refs["skuForm"].validate(valid => {
        if (valid) {
          // 创建一个新的数组，用于存储处理后的数据
          const newDataList = [];
          // 遍历 dataList 数组中的每一个对象
          this.dataList.forEach(item => {
            // 创建一个新的对象，用于存储处理后的键值对
            const newItem = {};

            // 创建一个新的对象，用于存储未在 skuAttr 中定义的属性
            const skuAttribute = {};

            // 遍历 item 对象的键值对
            for (const key in item) {
              // 检查当前键是否存在于 skuAttr 数组的 prop 中
              const propExists = this.skuAttr.some(attr => attr.prop === key);

              // 如果存在于 skuAttr 数组中，则保留该键值对，并拼接成字符串
              if (propExists) {
                newItem[key] = item[key];
              } else {
                // 如果不存在于 skuAttr 数组中，则添加到 skuAttribute 对象中
                skuAttribute[key] = item[key];
              }
            }

            // 将拼接后的字符串保存在 skuAttribute 键下
            newItem.skuAttribute = JSON.stringify(skuAttribute);

            // 将处理后的对象添加到 newDataList 数组中
            newDataList.push(newItem);
          });

          // 更新 dataList 数组为处理后的数组
          this.dataList = newDataList;
          addProductSkuList(this.dataList).then(res => {
            this.$modal.msgSuccess("操作成功");
            this.cancelSku();
            this.skuList = [];
          }).catch(err => {
            this.$modal.msgError(err);
          });
        }
      });
    },
    // 递归函数，用于生成所有可能的组合
    generateSKU(combination, index) {
      if (index === this.originalArray.length) {
        this.skuList.push({ ...combination });
        return;
      }

      let item = this.originalArray[index];
      let attrValues = item.attrValue.split(',');

      attrValues.forEach(value => {
        let newCombination = { ...combination };
        newCombination[item.attrName] = value;
        this.generateSKU(newCombination, index + 1);
      });
    },
    // 重新给表格赋值的方法
    refreshTableData() {
      // 使用 JSON 解析和字符串化，确保是深拷贝
      this.dataList = JSON.parse(JSON.stringify(this.dataList));
    },
    // 表单重置
    resetSku() {
      for (let key in this.skuForm) {
        this.skuForm[key] = null; // 或者设置为适当的初始值
      }
      this.resetForm("skuForm");
    },
  }
};
</script>
